package com.yuke.cloud.service.omc.controller.frontend;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.DateUtil;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.pmc.dto.ProdAttributeDto;
import com.yuke.cloud.service.api.pmc.dto.ProdSpecInfoDto;
import com.yuke.cloud.service.api.pmc.service.PmcFeignApi;
import com.yuke.cloud.service.api.smc.dto.ShopInfoDto;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.api.wmc.dto.StorageSpecInfoDto;
import com.yuke.cloud.service.api.wmc.dto.WmsFlowApiDto;
import com.yuke.cloud.service.api.wmc.service.WmcStorageFeignApi;
import com.yuke.cloud.service.omc.entity.OdsOrder;
import com.yuke.cloud.service.omc.entity.OdsOrderGoods;
import com.yuke.cloud.service.omc.entity.OdsStockGoods;
import com.yuke.cloud.service.omc.entity.OdsStockOrder;
import com.yuke.cloud.service.omc.service.OdsOrderGoodsService;
import com.yuke.cloud.service.omc.service.OdsOrderService;
import com.yuke.cloud.service.omc.service.OdsStockGoodsService;
import com.yuke.cloud.service.omc.service.OdsStockOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/ods/backorder")
@Slf4j
public class OdsorderBackController extends BaseController {
    @Resource
    private OdsOrderService odsOrderService;
    @Resource
    private OdsOrderGoodsService odsOrderGoodsService;
    @Resource
    private WmcStorageFeignApi wmcStorageFeignApi;
    @Resource
    private SmcFeignApi smcFeignApi;
    @Resource
    private PmcFeignApi pmcFeignApi;
    @Autowired
    private OdsStockOrderService odsStockOrderService;
    @Autowired
    private OdsStockGoodsService odsStockGoodsService;


    //获取普通用户和店铺需要发货的订单
    @PostMapping("/searchuserorder")
    public Wrapper<PageInfo<OdsOrder>> search(@RequestBody JSONObject jsonObject)  {

        if (jsonObject.get("warehouseId") != null && !jsonObject.get("warehouseId").equals("")) {
            Long warehouseId = Long.valueOf(jsonObject.get("warehouseId").toString());
            jsonObject.put("warehouseId",warehouseId);
        } else if (getGroupInfoDto().getGroupId() != null && getGroupInfoDto().getGroupId() > 1) {

            Long groupId = getGroupInfoDto().getGroupId();
            // 登录人为3级部门
            if (getGroupInfoDto().getLevel().toString().equals("3")) {
                groupId = getGroupInfoDto().getParentId();

            }
            jsonObject.put("groupId",groupId);
        }
        if (jsonObject.get("beginTime") != null && jsonObject.get("endTime") != null && !jsonObject.get("beginTime").equals("")) {
            Long beginTime = Long.parseLong(jsonObject.get("beginTime").toString());
            Long endTime = Long.parseLong(jsonObject.get("endTime").toString());
            jsonObject.put("beginTime",new Date(beginTime));
            jsonObject.put("endTime",new Date(endTime));
        }
        List<OdsOrder> search = odsOrderService.search(jsonObject);
        PageInfo pageInfo = new PageInfo(search);
        return WrapMapper.ok(pageInfo);
    }

    //获取店铺线上的订单，不需要发货
    @PostMapping("/searchshoporder")
    public Wrapper searchshoporder1(@RequestBody JSONObject jsonObject) throws ParseException {

        int page = 1;
        int size = 20;
        if (jsonObject.get("page") != null && jsonObject.get("size") != null) {
            page = Integer.valueOf(jsonObject.get("page").toString());
            size = Integer.valueOf(jsonObject.get("size").toString());
        }
        Example example = new Example(OdsStockOrder.class);
        example.setOrderByClause("create_time desc");
        Example.Criteria criteria = example.createCriteria();
        PageHelper.startPage(page, size);
        if (jsonObject.get("warehouseId") != null && !jsonObject.get("warehouseId").equals("")) {
            Long warehouseId = Long.valueOf(jsonObject.get("warehouseId").toString());
            /* List<Long> shipid = wmcStorageFeignApi.getshopidbywarehousename(warehouseId);*/
            criteria.andEqualTo("warehouseId", warehouseId);
        }
        if (jsonObject.get("orderId") != null && !jsonObject.get("orderId").equals("")) {
            Long orderId = Long.valueOf(jsonObject.get("orderId").toString());
            criteria.andEqualTo("orderId", orderId);
        }
        if (jsonObject.get("shopName") != null && !jsonObject.get("shopName").equals("")) {
            List<Long> shopids = smcFeignApi.getShopIdsShopName(jsonObject.get("shopName").toString());
            if (shopids == null || shopids.size() == 0) {
                List list2 = new ArrayList();
                PageInfo pageInfo = new PageInfo(list2);
                return WrapMapper.ok(pageInfo);
            }
            criteria.andIn("shopId", shopids);
        }
        //0：未付款；1：已付款
        if (jsonObject.get("payStatus") != null && !jsonObject.get("payStatus").equals("")) {
            criteria.andEqualTo("payStatus", jsonObject.get("payStatus"));
        }
        // 0：平台未确认；1：已确认；2：已完成；3：已取消（用户触发）；4：退货/退款（订单完成后还没入库时）；
        // 5：部分退货/退款（订单完成后还没入库时）；6：无效作废（管理员触发）
        if (jsonObject.get("orderStatus") != null && !jsonObject.get("orderStatus").equals("")) {
            criteria.andEqualTo("orderStatus", jsonObject.get("orderStatus"));
        }
        if (jsonObject.get("orderStatusTwo") != null && !jsonObject.get("orderStatusTwo").equals("")) {
            criteria.andBetween("orderStatus",0,3);
        }
        if (jsonObject.get("beginTime") != null && !jsonObject.get("beginTime").equals("")) {
            Object beginTime = jsonObject.get("beginTime").toString();
            Object endTime = jsonObject.get("endTime").toString();
            criteria.andLessThanOrEqualTo("createTime", endTime);
            criteria.andGreaterThan("createTime", beginTime);

        }
        List<OdsStockOrder> list = odsStockOrderService.selectByExample(example);
        if (list.size() == 0) {
            List list2 = new ArrayList();
            PageInfo pageInfo = new PageInfo(list2);
            return WrapMapper.ok(pageInfo);
        }
        List<Long> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            list1.add(list.get(i).getShopId());
        }
        List<ShopInfoDto> shopname = smcFeignApi.getShopInfoByShopIds(list1);
        if (shopname == null || shopname.size() == 0) {
            List list2 = new ArrayList();
            PageInfo pageInfo = new PageInfo(list2);
            return WrapMapper.ok(pageInfo);
        }
        List<Map> warehouseName = wmcStorageFeignApi.getWarehouseName(list1);
        if (warehouseName == null || warehouseName.size() == 0) {
            List list2 = new ArrayList();
            PageInfo pageInfo = new PageInfo(list2);
            return WrapMapper.ok(pageInfo);
        }
        for (int i = 0; i < list.size(); i++) {
            for (int k = 0; k < shopname.size(); k++) {
                if (list.get(i).getShopId().toString().equals(shopname.get(k).getShopId().toString())) {
                    list.get(i).setShopMobile(shopname.get(k).getMobile());
                    list.get(i).setShopUserName(shopname.get(k).getUserName());
                    list.get(i).setShopName(shopname.get(k).getShopName());
                    list.get(i).setWarehouseName(warehouseName.get(i).get("warehouseName").toString());
                    list.get(i).setWarehouseId(Long.valueOf(warehouseName.get(i).get("warehouseId").toString()));
                }
            }
        }
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    //普通查看订单详情
    @GetMapping("/getdetail/{orderid}")
    public Wrapper searchshoporder(@PathVariable("orderid") Long orderId) {
        OdsOrder byId = odsOrderService.findById(orderId);
        //通过orderid获取收货人地址
        Map map = odsOrderService.selectaddressbyid(byId.getRegionCountyId());
        List<Long> list = new ArrayList<>();
        list.add(byId.getShopId());
        List<ShopInfoDto> shopname = smcFeignApi.getShopInfoByShopIds(list);
        if (shopname == null || shopname.size() == 0) {
            return WrapMapper.error();
        }
        String shopName = shopname.get(0).getShopName();
        if (shopname != null || shopname.size() > 0) {
            byId.setShopName(shopName);
        }
        if (!map.isEmpty()) {
            byId.setRegionProvinceName(map.get("regionProvinceName").toString());
            byId.setRegionCountyName(map.get("regionCountyName").toString());
            byId.setRegionCityName(map.get("regionCityName").toString());
        }
        //获取商品主属性
        List<Long> specIdList = new ArrayList<>();
        Example example = new Example(OdsOrderGoods.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", orderId);
        //criteria.andNotEqualTo("goodsStatus", (byte)2); // 过滤退货申请2，已退货3
        criteria.andNotEqualTo("goodsStatus", (byte)3);
        criteria.andNotEqualTo("goodsStatus", (byte)5);
        List<OdsOrderGoods> odsOrderGoods2 = odsOrderGoodsService.selectByExample(example);
        specIdList = odsOrderGoods2.stream().map(OdsOrderGoods::getSpecId).collect(Collectors.toList());
        List<ProdAttributeDto> findProdAttribute = pmcFeignApi.getFindProdAttribute(specIdList);

        List<StorageSpecInfoDto> specInfoDtosBySpecIds = wmcStorageFeignApi.getAllStorageInfoBySpecIds(specIdList,byId.getShopId());
        if (specInfoDtosBySpecIds == null || specInfoDtosBySpecIds.size() == 0) {
            return WrapMapper.error();
        }
        byId.setWarehouseName(specInfoDtosBySpecIds.get(0).getWarehouseName());

        for (OdsOrderGoods select : odsOrderGoods2) {
            for (StorageSpecInfoDto item : specInfoDtosBySpecIds) {
                if (select.getSpecId().equals(item.getSpecId())) {

                    select.setCategoryId(item.getCategoryId());

                    if (byId.getOrderType().equals((byte)1)){
                        select.setPrice(item.getMarketPrice());
                     }else{
                        select.setPrice(item.getStockPrice());
                     }
                    select.setSpecId(item.getSpecId());
                    select.setSpecName(item.getSpecName());
                    select.setSpecCode(item.getSpecCode());
                    select.setHasRebate(item.getHasRebate());
                    select.setHasTying(item.getHasTying());
                    select.setImagesAddress(item.getBigPicture());
                    select.setBigPic(item.getBigPicture());
                    break;
                }
            }
            if (select.getCategoryId() == null){
                select.setCategoryId(0L);
                select.setSpecName("该商品已下架");
            }
        }

        if (findProdAttribute != null && findProdAttribute.size() > 0) {
            for (OdsOrderGoods orderGoods : odsOrderGoods2) {
                List<ProdAttributeDto> list1 = new ArrayList<>();
                for (ProdAttributeDto prodAttributeDto : findProdAttribute) {
                    if (orderGoods.getSpecId().toString().equals(prodAttributeDto.getSpecId().toString())) {
                        ProdAttributeDto prodAttributeDto1 = new ProdAttributeDto();
                        prodAttributeDto1.setAttributeName(prodAttributeDto.getAttributeName());
                        prodAttributeDto1.setAttributeValue(prodAttributeDto.getAttributeValue());
                        list1.add(prodAttributeDto1);
                    }
                }
                orderGoods.setProdAttributeDto(list1);
            }
        }

        List<OdsOrderGoods> collect = odsOrderGoods2.stream().sorted(Comparator.comparing(OdsOrderGoods::getCategoryId)).collect(Collectors.toList());
        byId.setGoodsList(collect);
        return WrapMapper.ok(byId);
    }

    //查看店铺订单详情
    @GetMapping("/getshopdetail/{orderid}")
    public Wrapper searchshoporder2(@PathVariable("orderid") Long orderid) {
        OdsStockOrder byId = odsStockOrderService.findById(orderid);
        Long shopId = byId.getShopId();
        List<Long> list1 = new ArrayList<>();
        list1.add(shopId);
        List<ShopInfoDto> shopname = smcFeignApi.getShopInfoByShopIds(list1);
        if (shopname == null || shopname.size() == 0) {
            return WrapMapper.error();
        }
        ShopInfoDto shopInfoDto = shopname.get(0);
        byId.setShopName(shopInfoDto.getShopName());
        byId.setShopUserName(shopInfoDto.getUserName());
        byId.setRegionProvinceName(shopInfoDto.getRegionProvinceName());
        byId.setRegionCountyName(shopInfoDto.getRegionCountyName());
        byId.setRegionCityName(shopInfoDto.getRegionCityName());
        byId.setAddress(shopInfoDto.getAddress());
        byId.setShopMobile(shopInfoDto.getMobile());
        Long orderId = byId.getStockOrderId();
        OdsStockGoods odsStockGoods = new OdsStockGoods();
        odsStockGoods.setStockOrderId(orderId);
        List<OdsStockGoods> select = odsStockGoodsService.select(odsStockGoods);
        if (select == null || select.size() == 0) {
            return WrapMapper.error();
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < select.size(); i++) {
            // mod by wg 20190423
//            if (i != select.size()) {
            if (i != (select.size() - 1)) {
                sb.append(select.get(i).getSpecId()).append(",");
            } else {
                sb.append(select.get(i).getSpecId());
            }
        }
        List<ProdSpecInfoDto> specInfoDtosBySpecIds = pmcFeignApi.getSpecInfoDtosBySpecIds(sb.toString());
        if (specInfoDtosBySpecIds == null || specInfoDtosBySpecIds.size() == 0) {
            return WrapMapper.error();
        }
        for (int i = 0; i < select.size(); i++) {
            select.get(i).setSpecName(specInfoDtosBySpecIds.get(i).getSpecName());
        }
        byId.setGoodsList(select);
        return WrapMapper.ok(byId);
    }

    //获取店铺线上的订单，不需要发货
    @PostMapping("/finishOrder")
    public Wrapper finishOrder(@RequestBody OdsOrder odsOrder){
        if (odsOrder != null && odsOrder.getOrderId() != null){
            OdsOrder order = odsOrderService.selectOne(odsOrder);
            order.setPayStatus((byte)1);
            order.setOrderStatus((byte)2);
            order.setShippingStatus((byte)3);
            order.setAmountPaid(odsOrder.getAmountPayable());
            order.setAcceptTime(new Date());
            odsOrderService.update(order);
        }
        return WrapMapper.ok();
    }

    //获取店铺需要打印的订单数，未发货的
    @PostMapping("/getOrderCount")
    public Wrapper getOrderCount(@RequestBody OdsOrder odsOrder){
        if (odsOrder != null && odsOrder.getUserId() != null){
            Example example = new Example(OdsOrder.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", odsOrder.getUserId());
            criteria.andEqualTo("orderType", (byte)2);
            criteria.andLessThan("orderStatus",(byte)2);
            criteria.andLessThan("shippingStatus",(byte)2);

            criteria.andBetween("createTime",DateUtil.lastDayTimeBegin().getTime(),DateUtil.nextDayTimeBegin().getTime());
            return WrapMapper.ok(odsOrderService.selectCountByExample(example));
        }
        return WrapMapper.error("参数错误！");
    }

    /**
     * 合并订单打印，只是合并提交数据，不是将两个订单打印
     * 从前一天0点到今天9点
     * @param odsOrder
     * @return
     */
    @PostMapping("/getOrderCombine")
    public Wrapper getOrderCombine(@RequestBody OdsOrder odsOrder){
        if (odsOrder == null || odsOrder.getUserId() == null){
            return WrapMapper.error("参数错误！");
        }

        Example example = new Example(OdsOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", odsOrder.getUserId());
        criteria.andEqualTo("orderType", (byte)2);
        criteria.andLessThan("orderStatus",(byte)2);
        criteria.andLessThan("shippingStatus",(byte)2);
        //筛选订单创建日期，一天前到今天9点
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE,-1);//一天

        Calendar d = Calendar.getInstance();
        d.setTime(new Date());
        d.set(Calendar.HOUR_OF_DAY, 9);//今天9点
        d.set(Calendar.MINUTE, 0);
        d.set(Calendar.SECOND, 0);

        criteria.andBetween("createTime",c.getTime(),d.getTime());
        List<OdsOrder> orderList = odsOrderService.selectByExample(example);


        for (OdsOrder item : orderList){
            Wrapper<OdsOrder> wrapperList = searchshoporder(item.getOrderId());
            if (wrapperList.getCode() == 200){
                OdsOrder oo = wrapperList.getResult();
                //item.setGoodsList(oo.getGoodsList());
                BeanUtils.copyProperties(oo,item);
            }

        }


        return WrapMapper.ok(orderList);
    }

    //获取店铺需要打印的订单数，未发货的
    @GetMapping("/selectOrderCount")
    public Wrapper selectOrderCount(@RequestParam Long userId) {
        Example example = new Example(OdsOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        criteria.andEqualTo("orderType", (byte) 2);
        criteria.andLessThan("orderStatus", (byte) 2);
        criteria.andLessThan("shippingStatus", (byte) 2);
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, -1);
        criteria.andBetween("createTime", c.getTime(), new Date());
        System.out.println(c.getTime());
        System.out.println(new Date());
        System.out.println(odsOrderService.selectCountByExample(example));
        if (odsOrderService.selectCountByExample(example) < 1) {
            return WrapMapper.ok(0);
        }
        return  WrapMapper.ok(1);
    }

    /**
    * 针对用户取消订单后，想恢复订单，继续派送的情况
    * 只对货到付款的情形有效,把订单状态更新到发货状态
     * 同时要修改库存
     */
//    @PostMapping("/renewOrder")
//    public Wrapper renewOrder(@RequestBody OdsOrder odsOrder){
//        if (PublicUtil.isEmpty(odsOrder) || PublicUtil.isEmpty(odsOrder.getOrderId())){
//            return WrapMapper.error("传入参数错误");
//        }
//
//        OdsOrder order = odsOrderService.selectOne(odsOrder);
//        if(PublicUtil.isNotEmpty(order)){
//            order.setPayStatus((byte)2);
//            order.setPayType((byte)0);
//            order.setOrderStatus((byte)1);
//            order.setShippingStatus((byte)2);
//            odsOrderService.update(order);
//        }
//
//        //修改库存
//
//        return WrapMapper.ok();
//    }


    //获取普通用户和店铺需要发货的订单
    @PostMapping("/searchOrderFlow")
    public Wrapper<PageInfo<OdsOrder>> searchOrderFlow(@RequestBody JSONObject jsonObject)  {

        if (jsonObject.get("warehouseId") != null && !jsonObject.get("warehouseId").equals("")) {
            Long warehouseId = Long.valueOf(jsonObject.get("warehouseId").toString());
            jsonObject.put("warehouseId",warehouseId);
        } else if (getGroupInfoDto().getGroupId() != null && getGroupInfoDto().getGroupId() > 1) {

            Long groupId = getGroupInfoDto().getGroupId();
            // 登录人为3级部门
            if (getGroupInfoDto().getLevel().toString().equals("3")) {
                groupId = getGroupInfoDto().getParentId();

            }
            jsonObject.put("groupId",groupId);
        }
        if (jsonObject.get("beginTime") != null && jsonObject.get("endTime") != null && !jsonObject.get("beginTime").equals("")) {
            Long beginTime = Long.parseLong(jsonObject.get("beginTime").toString());
            Long endTime = Long.parseLong(jsonObject.get("endTime").toString());
            jsonObject.put("beginTime",new Date(beginTime));
            jsonObject.put("endTime",new Date(endTime));
        }
        List<OdsOrder> search = odsOrderService.search(jsonObject);
        PageInfo pageInfo = new PageInfo(search);
        List<Long> collect = search.stream().map(OdsOrder::getOrderId).collect(Collectors.toList());
        List<WmsFlowApiDto> flowList = wmcStorageFeignApi.findOrderFlow(collect);
        if (flowList==null||flowList.size()==0){
            return null;
        }

        for (OdsOrder odsOrder : search) {
            List<WmsFlowApiDto> wmsFlowApiDtos = new ArrayList<>();
            for (WmsFlowApiDto wmsFlowApiDto : flowList) {
                if (odsOrder.getOrderId().equals(wmsFlowApiDto.getFlowOrderId())) {
                    wmsFlowApiDtos.add(wmsFlowApiDto);
                    odsOrder.setFlowList(wmsFlowApiDtos);
                }
            }
        }
        return WrapMapper.ok(pageInfo);
    }

}
